package com.jflm.util;

import java.security.PrivateKey;
import java.security.cert.X509Certificate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cat.util.charset.Base64;


public class SignHandler {
	private static Log _log = LogFactory.getLog(SignHandler.class);

	/**
	 * 对报文签名进行验签
	 * @param channel 渠道号（根据渠道号来进行验证签名）
	 * @param signStr 拼装后未加签名串
	 * @param signKey 通信传入签名
	 * @return boolean 验签结果
	 * */
	public static boolean doCheckSign( String signStr, String signKey)throws Exception {
		boolean verify = true; 
		try{
				verify = checkSign(signStr, signKey);
		}catch(Exception e){
			verify = false;
			_log.error(e);
		}
		return verify;
	}
	
	private static boolean checkSign(String signStr, String sign) throws Exception {
		try {
			_log.debug("# 开始验证签名信息...");
			_log.debug("# 待签串..."+signStr);
			
			String certFile_Path = PropertiesUtils.getProperty("check_certFile_Path");
//			String cert_path = DynAttrMgr.getInstance().getProperty("plat.cert_path", null);
			String keyFile = certFile_Path;
			_log.debug("# 平台公钥地址=="+keyFile);
			if(certFile_Path==null){
				throw new Exception("获取公钥地址失败...");
			}
			byte[] certData = FileUtil.getFileContent(keyFile);

			X509Certificate cert = SignUtil.genCertificate(certData);

			byte[] signData = Base64.decode(sign);

			return SignUtil.verify(cert, signStr.getBytes(), signData);
		} catch (Exception e) {
			e.printStackTrace();
			_log.error(e);
			throw new Exception("验证签名信息异常",e);
		}
	}
	/**
	 * 生成签名信息
	 * @param String signValue 拼装后未加签名串
	 * */
	public static String doGenerateSign(String signValue) throws Exception {
		_log.debug("# 开始生成签名信息......");
		try{
			String certFile_Path = PropertiesUtils.getProperty("private_certFile_Path");
			
			_log.debug("# 平台私钥地址=="+certFile_Path);
			if(certFile_Path==null ){
				throw new Exception("获取私钥地址失败...");
			}
			signValue = generateSign(signValue, certFile_Path);
		}catch(Exception e){
			_log.error(e);
			throw new Exception("生成签名信息异常");
		}
		return signValue;
	}
	
	private static String generateSign(String dataString, String keyFile) throws Exception {
		try {
			_log.debug("# 开始生成签名信息");
			byte[] key = FileUtil.getFileContent(keyFile);

			PrivateKey pk = SignUtil.genPrivateKey(key);

			byte[] signData = SignUtil.sign(pk, dataString.getBytes());

			String pemSignData = Base64.encode(signData);

			return pemSignData;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}

	}
	
}
